<script setup lang="ts">
import { Pages } from '@typings/pages'
import { Plus, Share } from '@element-plus/icons-vue'
import YkEmptyBox from '@yk/components/empty-box/YkEmptyBox.vue'
import { EmptyEnum, EmptyState } from '@yk/components/empty-box/type'
import { ElForm } from 'element-plus'
import { getSceneListAPI } from '@/api/scene'
import { SceneDTO } from '@/api/entity/scene'
import { ObjectUtil } from '@utils/object-util'
import { addSelfConfigAPI, delSelfConfigAPI, editSelfConfigAPI, getSelfConfigListAPI } from '@/api/self-config'
import { ConfigurationDTO, SelfConfigSaveForm } from '@/api/entity/self-config'
import { phoneRule, required } from '@utils/form-rule'
import { getEncryptVStr } from '@/router/interceptor/security'
import YkDatePicker from '@yk/components/date-picker/YkDatePicker.vue'
import { selfShareByPhoneAPI, unShareDeviceAPI, unShareSelfAPI } from '@/api/share'
import { PreferenceDB } from '@utils/indexedDB/preference'

const router = useRouter()
defineOptions({ name: 'LogIndex' })

onMounted(() => {
  searchHandle()
})

// region TODO 查询
const searchParams = reactive({
  name: ''
})
function searchHandle () {
  pages.pageNum = 1
  getSelfList()
}
// endregion

// region TODO 列表数据
const pages = reactive(new Pages())
const selfList = ref<ConfigurationDTO[]>([])
const selfListState = shallowRef<EmptyState>(EmptyEnum.NONE)
function getSelfList () {
  const loading = ElLoading.service()
  getSelfConfigListAPI(searchParams).then((res) => {
    res.result().then((rdata) => {
      selfList.value = rdata.data
      if (selfList.value.length) {
        selfListState.value = EmptyEnum.SUCCESS
      } else {
        selfListState.value = EmptyEnum.EMPTY
      }
    })
  }).finally(loading.close)
}

function delSelfListItem (id: string) {
  ElMessageBox.confirm('确认删除此组态？', '删除提醒').then(() => {
    const loading = ElLoading.service()
    delSelfConfigAPI({ id }).then((res) => {
      res.result().then(() => {
        ElMessage.success('删除成功')
        getSelfList()
        getSceneList()
      })
    }).finally(loading.close)
  })
}
// endregion

// region TODO 场景
const sceneList = shallowRef<SceneDTO[]>(null)
function getSceneList () {
  getSceneListAPI().then((res) => {
    res.result().then((rdata) => {
      sceneList.value = rdata.data
    })
  })
}
// endregion

// region TODO 添加/修改表单
const saveForm = ref(new SelfConfigSaveForm())
const saveFormRules = {
  name: [required('组态名称不可为空')],
  groupId: [required.change('场景不可为空')]
}
const saveFormRef = shallowRef<InstanceType<typeof ElForm>>()

// 对话框
const saveFormDialogModel = ref(false)
function showSaveFormDialog (item?: ConfigurationDTO) {
  saveFormDialogModel.value = true
  if (!sceneList.value) getSceneList()
  if (item) {
    nextTick(() => {
      ObjectUtil.updateVal(saveForm.value, item)
    })
  }
}
function closeSaveFormDialog () {
  saveFormDialogModel.value = false
  saveFormRef.value.resetFields()
  saveForm.value.id = null
}
function submitSaveForm () {
  saveFormRef.value.validate().then(() => {
    const loading = ElLoading.service()
    const params = ObjectUtil.copy(saveForm.value)
    const result = saveForm.value.id ? editSelfConfigAPI(params) : addSelfConfigAPI(params)
    result.then((res) => {
      res.result().then(() => {
        ElMessage.success('保存成功')
        closeSaveFormDialog()
        getSelfList()
        if (!saveForm.value.id) getSceneList()
      })
    }).finally(loading.close)
  })
}
// endregion

// region TODO 跳转
function toEditorDraw (id: string) {
  window.open('/#/editor-draw?v=' + getEncryptVStr({ query: { id } }), '_blank')
}
function toShowDraw (id: string) {
  window.open('/#/show-draw?v=' + getEncryptVStr({ query: { id } }), '_blank')
}
function toShareList (id: string) {
  router.push({ name: 'SelfShareList', query: { id } })
}
// endregion

// region TODO 分享组态
const shareDialogModel = ref(false)
const shareSelfFormRef = shallowRef<InstanceType<typeof ElForm>>()
const shareSelfForm = ref<Parameters<typeof selfShareByPhoneAPI>[0]>({ expiredTime: '' })
const shareSelfFormRules = shallowRef({
  phone: [required('手机号为必填项'), phoneRule]
})

function showShareDialog (item: ConfigurationDTO) {
  shareSelfForm.value = { configurationId: item.id, roleType: '0', expiredTime: '' }
  shareDialogModel.value = true
}
function closeShareDialog () {
  if (!shareDialogModel.value) return
  shareDialogModel.value = false
  shareSelfFormRef.value.resetFields()
}
function submitShareSelfForm () {
  const loading = ElLoading.service()
  shareSelfFormRef.value.validate().then(() => {
    selfShareByPhoneAPI(shareSelfForm.value).then((res) => {
      res.result().then(() => {
        ElMessage.success('已分享')
        closeShareDialog()
      })
    })
  }).finally(loading.close)
}

// region TODO 解绑分享
function unShareSelf (id: string, index: number) {
  ElMessageBox.confirm('解绑组态后无法继续查看组态画面，是否继续？', '解绑提醒').then(res => {
    const loading = ElLoading.service()
    unShareSelfAPI({ id }).then((res) => {
      res.result().then(() => {
        ElMessage.success('已解除分享')
        selfList.value.splice(index, 1)
      })
    }).finally(loading.close)
  })
}
// endregion
// endregion
</script>

<template>
  <div class="layout_view d-flex" style="min-height: 100%">
    <div class="c_card-page w-100">
      <div class="c_card_header c_card-title bor-divider-b">组态画面</div>
      <!--搜索表单-->
      <el-form inline class="c_form-search mt-16" @submit.prevent="searchHandle">
        <el-form-item label="组态名称">
          <el-input v-model="searchParams.name" placeholder="请输入组态名称搜索" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchHandle">查询</el-button>
        </el-form-item>
      </el-form>
      <!--功能栏-->
      <div>
        <el-button type="primary" :icon="Plus as any" @click="showSaveFormDialog()">添加组态</el-button>
      </div>
      <!--列表-->
      <yk-empty-box :state="selfListState" :image-size="172">
        <div class="d-grid self-config-list" style="min-height: 400px;">
          <div v-for="(item, index) in selfList" :key="item.id" style="height: 250px" class="self-config-list__item bor-divider">
            <!--图片-->
            <img src="./images/default-self-config.png" style="width: 52px;aspect-ratio: 1;" alt="">
            <div class="mt-20 text-center" style="min-height: 48px;">
              <p class="text-color-primary fs-16 fw-7">{{ item.name }}</p>
              <p class="color-secondary fs-14 mt-8">{{ item.groupName }}</p>
            </div>
            <!--按钮组-->
            <div class="c_form__submit-btn mt-12">
              <el-button v-if="item.edit" type="primary" plain @click="toEditorDraw(item.id)">设计</el-button>
              <el-button type="primary" @click="toShowDraw(item.id)">运行</el-button>
            </div>
            <!--按钮组-->
            <div class="btn-group bor-divider-t">
              <template v-if="item.edit">
                <el-link type="primary" @click="showSaveFormDialog(item)">编辑</el-link>
                <el-link type="primary" class="bor-divider-l" @click="showShareDialog(item)">分享</el-link>
                <el-link type="primary" class="bor-divider-l" @click="toShareList(item.id)">分享列表</el-link>
                <el-link type="danger" class="bor-divider-l" @click="delSelfListItem(item.id)">删除</el-link>
              </template>
              <el-link v-else type="danger" @click="unShareSelf(item.id, index)">解绑分享</el-link>
            </div>
          </div>
        </div>
        <template #footer>
          <span class="text-color-placeholder fs-14">还没有组态画面，<el-link type="primary" @click="showSaveFormDialog()">添加组态</el-link></span>
        </template>
      </yk-empty-box>
      <!--添加/修改表单-->
      <el-dialog
        v-model.trim="saveFormDialogModel" :title="saveForm.id ? '编辑组态' : '添加组态'" width="475px"
        :close-on-click-modal="false" draggable :modal="false"
        @close="closeSaveFormDialog"
      >
        <el-form
          ref="saveFormRef" class="c_form-save" :model="saveForm"
          :rules="saveFormRules" style="margin-top: 20px;"
          label-width="100px"
        >
          <el-form-item label="组态名称：" prop="name">
            <el-input v-model="saveForm.name" placeholder="请输入组态名称" :maxlength="12" show-word-limit />
          </el-form-item>
          <el-form-item label="场景：" prop="groupId">
            <div class="d-flex-align-center">
              <el-select v-model="saveForm.groupId" :disabled="Boolean(saveForm.id)" placeholder="请选择场景" filterable>
                <template #header>
                  <span class="fs-12 c_form-tip">仅可选择未创建组态的场景</span>
                </template>
                <el-option
                  v-for="item in sceneList" :key="item.id"
                  :value="item.id" :label="item.name" :disabled="item.existsConfiguration"
                />
              </el-select>
              <refresh-btn class="cursor-pointer ml-2 fs-24 color-primary" @click="getSceneList" />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="c_form__submit-btn">
            <el-button type="primary" plain @click="closeSaveFormDialog">取消</el-button>
            <el-button type="primary" @click="submitSaveForm">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <!--分享组态-->
      <el-dialog
        v-model="shareDialogModel" title="分享组态" width="400px"
        :close-on-click-modal="false" draggable :modal="false"
        @close="closeShareDialog"
      >
        <el-form
          ref="shareSelfFormRef"
          :model="shareSelfForm" :rules="shareSelfFormRules"
          label-width="100px" style="margin-top: 20px;"
          class="c_form-save"
        >
          <el-form-item label="分享人" prop="phone">
            <el-input v-model="shareSelfForm.phone" placeholder="请输入对方的手机号" />
          </el-form-item>
          <el-form-item label="共享有效期：" prop="expiredTime">
            <yk-date-picker
              v-model="shareSelfForm.expiredTime"
              type="datetime"
              optional-scope="after"
              placeholder="选择共享有效期"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <div class="d-flex justify-content-end w-100">
              <el-button type="primary" plain @click="closeShareDialog">取消</el-button>
              <el-button type="primary" @click="submitShareSelfForm()">分享</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped lang="scss">
.self-config-list {
  margin-top: 17px;
  grid-template-columns: repeat(auto-fill, minmax(267px, 1fr));
  grid-gap: 16px;
  .self-config-list__item {
    padding: 32px 0 0;
    flex-direction: column;
    @include d-flex(center, flex-start);
    height: 250px;
    border-radius: 8px;
    overflow: hidden;
    position: relative;
    .btn-group {
      position: absolute;
      height: 36px;
      bottom: 0;
      width: 100%;
      display: flex;
      a {
        flex: 1;
      }
    }
  }
}
</style>
